#include "Composite.h"

#include <iostream>
#include <algorithm>
using namespace std;

Component::Component()
{
    cout << "Component::Component()" << endl;
}

Component::~Component()
{
    cout << "Component::~Component()" << endl;
}

void Component::Add(Component* pChild)
{
    cout << "Component::Add(Component* pChild)" << endl;
}

void Component::Remove(Component* pChild)
{
    cout << "Component::Remove(Component* pChild)" << endl;
}

Component* Component::GetChild(int nIndex)
{
    cout << "Component::GetChild(" << nIndex << ")" << endl;
    return nullptr;
}

Leaf::Leaf()
{
    cout << "Leaf::Leaf()" << endl;
}

Leaf::~Leaf()
{
    cout << "Leaf::~Leaf()" << endl;
}

void Leaf::Operation()
{
    cout << "Leaf::Operation()" << endl;
}

Composite::Composite()
{
    cout << "Composite::Composite()" << endl;
}

Composite::~Composite()
{
    cout << "Composite::~Composite()" << endl;
    list<Component*>::iterator iter1;
    list<Component*>::iterator iter2;
    list<Component*>::iterator tmp;

    for (iter1 = _ListOfComponent.begin(), iter2 = _ListOfComponent.end(); iter1 != iter2;) {
        tmp = iter1;
        ++iter1;
        delete(*tmp);
    }
}

void Composite::Add(Component* pChild)
{
    cout << "Composite::Add(Component* pChild)" << endl;
    _ListOfComponent.push_back(pChild);
}

void Composite::Remove(Component* pChild)
{
    cout << "Composite::Remove(Component* pChild)" << endl;
    list<Component*>::iterator iter;
    iter = find(_ListOfComponent.begin(), _ListOfComponent.end(), pChild);
    if (iter != _ListOfComponent.end()) {
        _ListOfComponent.erase(iter);
    }
}

Component* Composite::GetChild(int nIndex)
{
    cout << "Composite::GetChild(" << nIndex << ")" << endl;
    if (nIndex <= 0 || nIndex > _ListOfComponent.size()) {
        return nullptr;
    }

    list<Component*>::iterator iter1;
    list<Component*>::iterator iter2;
    int i;
    for (i = 1, iter1 = _ListOfComponent.begin(), iter2 = _ListOfComponent.end(); iter1 != iter2; ++iter1, ++i) {
        if (i == nIndex) {
            break;
        }
    }
    
    return (*iter1);
}

void Composite::Operation()
{
    cout << "Composite::Operation()" << endl;
    list<Component*>::iterator iter1;
    list<Component*>::iterator iter2;
    for (iter1 = _ListOfComponent.begin(), iter2 = _ListOfComponent.end(); iter1 != iter2; ++iter1) {
        (*iter1)->Operation();
    }
}


